package com.mokairui.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @Description 分治 适合任务可以拆分
 * @Author Mokairui
 * @Since 2021/10/6
 */
@Slf4j(topic = "c.forkJoin")
public class ForkJoinThreadPool {
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool(4);
        System.out.println(pool.invoke(new MyTask(5)));
    }

}

@Slf4j(topic = "c.myTask")
class MyTask extends RecursiveTask<Integer> {

    private int n;

    public MyTask(int n) {
        this.n = n;
    }

    @Override
    public String toString() {
        return String.format("{%s}", n);
    }

    @Override
    protected Integer compute() {
        // 终止条件
        if (n == 1) {
            log.debug("join() {}", n);
            return 1;
        }
        MyTask t1 = new MyTask(n - 1);
        t1.fork(); // 让一个线程去执行此任务
        log.debug("fork() {} + {}", n, t1);
        int result = n + t1.join(); // 获取任务结果
        log.debug("result() {} + {} = {}", n, t1, result);
        return result;
    }
}
